<template>
	<view>
		<cu-custom bgColor="bg-orange" customBack="true" addBack="true"  @add="add" >
			<block slot="backText">
				<van-icon name="replay" class="refreshbtn" size="50rpx" @click='update'/>
				<van-icon name="plus" class="add" size="50rpx" @click='add'/>
			</block>
		  <block slot="content" >
			 <view @click="selectWeek">
				 <text>第{{nowWeek}}周</text>
				 <van-icon name="arrow-down" />
			 </view>
		  </block>
		</cu-custom>
		<view class="container">
		  <view class="weeklist">
			  <view class="now-month">
				  <text>{{sevenDays[0].month}}</text>
				  <text>月</text>
			  </view>
			  <view :class="['week-item', {'active': nowmonth === value.month && nowday === value.day1}]"  v-for="(value,index) in sevenDays" :key=index>
				  <text class="weekname">周{{weekIndexText[index]}}</text>
				  <text class="weekdate">{{value.day1 == 1 ? ((value.month == 12 ? 1 : (value.month + 1)) + '月') 
											:(value.day1 < 9 ? '0' : '' ) + value.day1 + '日' }}</text>
			  </view>
		  </view>
		  <view class="coursecontent">
		  	<view class="coursenums">
		  		<view class="coursenum" v-for="key,index in 12" :key="index">
		  			{{key+1>9?key+1:'0'+(key+1)}}
		  		</view>
		  	</view>
		  	<view class="courselist">
		  		<view class="courseitem" v-for="(course,index) in courseinfo" :key="index" 
				:style="{ height: (course.end - course.begin+1) * 120 + 'rpx', 
				top:(course.begin-1)*120+ 'rpx',left:(course.day-1)*((windowWidth*2-50)/7) + 'rpx'}" v-if="course.weeknum.includes(nowWeek)"
				@click="coursedetail(course)">
		  		  <view class="courseitem-content" :style="{ 'background-color': course.color }">
		  		    {{ course.name }}@{{ course.address }}
		  		  </view>
		  		</view>
		  	</view>
		  </view>
		</view>
		
		<van-popup :show="showSwitchWeek" position="bottom" @close="hideSwitchWeek" :round="true">
		    <view class="switch-week__popup">
		      <view class="switch-week__title">切换周数</view>
		      <view class="switch-week__list">
		        <view v-for="(item, index) in totalWeek" :key="index" class="switch-week__item">
		          <view @tap="switchWeek(item + 1)" :class="['switch-week__item-box', {'active': nowWeek === index + 1}]">
		            {{item + 1}}
		          </view>
		        </view>
		      </view>
		    </view>
		  </van-popup>
	</view>
</template>


<script>
	import {
		mapMutations,
		mapState
	} from 'vuex'
	export default {
		computed: {
			...mapState('m_course', ['courseinfo']),
			...mapState('m_user', ['token', 'userinfo'])
			},
		data() {
			return {
				windowWidth: '',
				showSwitchWeek: false,
				totalWeek: 20, // 周总数
				nowWeek: 1, // 当前周
				rightWeek: 1, //当地时间所在周
				firstDate: '2023/8/28', //开学时间
				weekIndexText: ['一', '二', '三', '四', '五', '六', '日'],
				weekCalendar: [1, 2, 3, 4, 5, 6, 7],
				sevenDays: [],
				nowyear: '',
				nowmonth: '',
				nowday: '',

			};
		},
		watch:{
			token(newValue,oldValue){
				this.getcourse()
			}
		},
		onLoad() {
			if (!this.courseinfo.length) this.getcourse()
			const {
				windowWidth
			} = wx.getSystemInfoSync()
			this.windowWidth = windowWidth

			//获取当地时间
			let date = new Date();
			this.nowyear = date.getFullYear(); // 获取当前的年份
			this.nowmonth = date.getMonth() + 1; // 获取当前的月份（注意月份从0开始，需要加1获取正确月份）
			this.nowday = date.getDate(); // 获取当前的日期

			//获取当地时间所在周
			this.getrightWeek()
			this.nowWeek = this.rightWeek
			this.getWeekDate(this.rightWeek)

		},
		onShow() {
			if (!this.courseinfo.length) this.getcourse()
			this.switchWeekFn(this.rightWeek)
		},
		methods: {
			...mapMutations('m_course', ['updateCourseInfo']),
			async getcourse() {
				if(this.token==='') return
				const data = await uni.$http.get('/get/getcourse')
				if (data.data.status === 0) {
					data.data.data.forEach(course => {
						course.color = this.getRandomColor();
					});

					this.updateCourseInfo(data.data.data)
				}
			},
			getRandomColor() {
				let r = Math.floor(Math.random() * 256); // 生成随机的红色值（0-255）
				let g = Math.floor(Math.random() * 256); // 生成随机的绿色值（0-255）
				let b = Math.floor(Math.random() * 256); // 生成随机的蓝色值（0-255）
				return "rgb(" + r + ", " + g + ", " + b + ")";
			},
			selectWeek() {
				if(this.token==='') return
				this.showSwitchWeek = true

			},
			switchWeek(week) {
				this.showSwitchWeek = false
				this.switchWeekFn(week)
			},
			//计算当前周
			getrightWeek() {
				// 获取当前日期
				const currentDate = new Date();
				// 获取当前日期所在的年份、月份和天数
				const year = currentDate.getFullYear();
				const month = currentDate.getMonth() + 1; // 注意，月份从 0 开始，需要加 1
				const day = currentDate.getDate();
				// 获取一周的第一天（假设每周的第一天是周一）
				const firstDayOfWeek = new Date(year, month - 1, day - currentDate.getDay() + 1);
				// 获取第一周的起始日期（假设第一周开始于 2023.8.28）
				const time = this.firstDate.split('/');
				const firstWeekStartDate = new Date(time[0], time[1] - 1, time[2]);
				// 计算当前周数（从第一周开始计算）
				this.rightWeek = Math.ceil((currentDate - firstWeekStartDate) / (7 * 24 * 60 * 60 * 1000));
			},
			//计算指定周数的七天
			getWeekDate(weekNumber) {
				this.sevenDays = []
				const time = this.firstDate.split('/');
				let startDate = new Date(time[0], time[1] - 1, time[2]); // 设置第一周的第一天，即2023年8月28日
				startDate.setDate(startDate.getDate() + (weekNumber - 1) * 7); // 根据指定周数计算第一天的日期
				for (let i = 0; i < 7; i++) {
					let day = new Date(startDate);
					day.setDate(day.getDate() + i);

					let date = new Date(day);
					let year = date.getFullYear(); // 年份：2023
					let month = date.getMonth() + 1; // 月份：10（注意月份从0开始，需要加1获取正确月份）
					let day1 = date.getDate(); // 日期：15
					this.sevenDays.push({
						year,
						month,
						day1
					});
				}
			},
			// 切换周数
			switchWeekFn(week) {
				if(this.token==='') return
				this.nowWeek = week
				this.getWeekDate(this.nowWeek)
			},
			hideSwitchWeek() {
				this.showSwitchWeek = false
			},
			update() {
				if(this.token==='') return
				this.nowWeek = this.rightWeek
				this.getWeekDate(this.rightWeek)
			},
			add() {
				if(this.token==='') return
				uni.navigateTo({
					url: '/pages/addcourse/addcourse'
				})
			},
			coursedetail(course,index) {
				const dataStr = JSON.stringify(course);
				//encodeURIComponent 是 JavaScript 中的一个全局函数，用于将字符串作为 URI 组件进行编码。
				uni.navigateTo({
				    url: '/pages/coursedetail/coursedetail?data=' + encodeURIComponent(dataStr) + '&index=' + index
				});
			}
		},


	}
</script>

<style lang="less">
.refreshbtn{
	width: 55rpx;
	height: 52rpx;
}
.weeklist{
	position: fixed;
	left: 0;
	width: 100%;
	height: 92rpx;
	background-color: #F5F6F7;
	display: flex;
	align-items: center;
	.now-month{
		width: 50rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 24rpx;
		color: #666666;
	}
	.week-item{
		width: calc((100% - 50rpx)/7);
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		.weekname{
			font-size: 24rpx;
			color: #444444;
		}
		.weekdate{
			font-size: 20rpx;
			color: #a1a1a1;
		}
	}
	.active .weekname,
	.active .weekdate{
		background-color: orange;
	}
	
}
.coursecontent{
	 width: 100%;
	  padding-top: 92rpx;
	  display: flex;
	.coursenums{
		width: 50rpx;
		  display: flex;
		  flex-direction: column;
		  align-items: center;
		  justify-content: center;
		  background: #f5f6f7;
		.coursenum{
			 height: 120rpx;
			  display: flex;
			  align-items: center;
			  justify-content: center;
			  font-size: 24rpx;
			  color: #999999;
		}
	}
	.courselist{
	 width: 100%;
	  height: 100%;
	  position: relative;
		.courseitem{
			position: absolute;
			width: calc((100% - 50rpx) / 7);
			padding: 2rpx;
			  .courseitem-content{
				   width: 100%;
				    height: 100%;
				    border-radius: 8rpx;
				    font-size: 24rpx;
				    color: #ffffff;
				    text-align: center;
			  }
		}
	}

}
.switch-week__popup {
  padding: 30rpx;
  .switch-week__title {
    text-align: center;
    font-size: 34rpx;
    font-weight: 500;
  }
  .switch-week__list {
    display: flex;
    flex-wrap: wrap;
    margin-top: 30rpx;
	.switch-week__item {
	  width: 20%;
	  padding: 10rpx;
	  .switch-week__item-box {
	    width: 100%;
	    height: 100rpx;
	    background-color: #eee;
	    display: flex;
	    align-items: center;
	    justify-content: center;
	    border-radius: 12rpx;
	  }
	  .switch-week__item-box.active {
		background-color: orange;
	    color: #fff;
	    font-size: 32rpx;
	    font-weight: bold;
	  }
	}
  }
}
</style>